package com.hyopt.modules.app.controller;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.hyopt.common.utils.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName ChatGPT
 * @Description TODO
 * @Author lijie
 * @Date 2023/2/8 11:18 星期三
 * @Version 1.0
 */
@Component
@Service
@Slf4j
public class ChatGPT {

    @Autowired
    private RedisUtils redisUtils;

    public static final String ak = "552ff24d338766734cd6231f966e22c2";

    public static final String sk = "3103f70afb2f2ed3d1471d2ad81dd73e";

    public static void main(String[] args) throws Exception {
        String s = LingYang.aesDecrypt("PLOfniAkkpPaCGFhN4VkRfqkDoNWT8Cs335P6070Yzr71vj+DX7psXsOtUA1H2srurh1du+EkraNYPJPzdOx5q+QP/ZN5uZahr43aZJSgQg=",LingYang.AESKey,"utf-8");
        System.out.println(s);
        String a = LingYang.aesEncrypt("{\"token\":\"1676276575000001-OPEN-b0bdf3a33cb24c81b39962f44286df71\"}",LingYang.AESKey,"utf-8");
        System.out.println(a);
    }

    /**
     * 聊天对话
     */
    public Object chat(String content) {
        // 请求程序员盒子获取Token
        log.info("已进入调用链路，问题为{}" + content);
        String token = redisUtils.get("token");
        if (StrUtil.isBlank(token)) {
            token = GptTokenUtil.getToken(ak, sk);
               if (StrUtil.isNotBlank(token)){
                   redisUtils.set("token", token, 18000);
               }else{
                   return "无法获取chatGPT签发的apikey，请稍后再试";
               }
        }
        log.info("使用token为{}" + token);
//        String token = "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";
//        String token = "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";
        // 请求头参数
//        Map<String, String> headers = this.buildHeaders(token);
        // 对话模型、输入 body
        Map<String, Object> param = ChatGPT.buildChatParam(content);
        // openAi 对话接口
        String completionsApi = "https://api.openai.com/v1/completions";
        // 请求并返回对话结果
        JSONObject jsonObject = ChatGPT.buildChatParam(content);
        HttpRequest request = HttpUtil.createPost(completionsApi);
        request.header("Content-Type", "application/json");
        request.header("Authorization", "Bearer ".concat(token));
        request.body(param.toString());
        request.setReadTimeout(20000);
        HttpResponse response = request.execute();
        com.alibaba.fastjson.JSONObject responseJson = null;
        Object o = null;
        String body = response.body();
        log.info("调用结果{}" + body);
        if (response.getStatus() == 200) {
            responseJson = com.alibaba.fastjson.JSONObject.parseObject(body);
            JSONArray array = responseJson.getJSONArray("choices");
            o = ((com.alibaba.fastjson.JSONObject) array.get(0)).get("text");
        } else {
            // 备用方案--非chatGPT模型,常规AI对话接口
            String url = "https://chatgpt.ruolikongjian.cn/chat/say";
            HttpRequest httpRequest = HttpUtil.createPost(url);
            httpRequest.body("{\"say\":\"" + content+ "\"}");
            HttpResponse ryRes = httpRequest.execute();
            o = ryRes.body();
        }
        System.out.println(o);
        return o;
    }



    /**
     * 构造请求头
     */
    private static Map<String, String> buildHeaders(String token) {
        Map<String, String> headers = new HashMap<>();
        headers.put("Content-Type", "application/json");
        headers.put("Authorization", "Bearer ".concat(token));
        return headers;
    }

    /**
     * 构造请求参数
     */
    private static JSONObject buildChatParam(String content) {
        JSONObject param = JSONUtil.createObj();
        param.put("model", "text-davinci-003"); // 对话模型
        param.put("prompt", content);
        param.put("max_tokens", 3000);
        param.put("temperature", 0.8);
        return param;
    }
}
